package com.zycfc.zsf.boot.web.converter;

import com.zycfc.zsf.boot.data.enums.*;
import org.springframework.core.convert.converter.*;
import org.slf4j.*;
import com.zycfc.zsf.boot.data.util.*;

public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum>
{
    private static final Logger log;
    
    public <T extends BaseEnum> Converter<String, T> getConverter(final Class<T> targetType) {
        return (Converter<String, T>)new StringToBaseEnum((Class<Enum>)targetType);
    }
    
    static {
        log = LoggerFactory.getLogger((Class)StringToBaseEnumConverterFactory.class);
    }
    
    private class StringToBaseEnum<T extends Enum<? extends BaseEnum>> implements Converter<String, T>
    {
        private final Class<T> enumType;
        
        public StringToBaseEnum(final Class<T> enumType) {
            this.enumType = enumType;
        }
        
        public T convert(final String source) {
            if (null == source || source.isEmpty()) {
                return null;
            }
            try {
                final Integer code = Integer.parseInt(source);
                return (T)EnumUtil.getByCode((Class)this.enumType, (int)code);
            }
            catch (Throwable t) {
                StringToBaseEnumConverterFactory.log.error(t.getMessage(), t);
                return (T)EnumUtil.getByName((Class)this.enumType, source);
            }
        }
    }
}
